package com.fanrenqiji.modules.sys.web;

import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.modules.sys.entity.Area;
import com.fanrenqiji.modules.sys.service.AreaService;
import com.fanrenqiji.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年2月11日 下午2:00:29
 * @description 大区的控制器
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/area/")
public class AreaController extends BaseController {

	@Autowired
	private AreaService areaService;

	@ModelAttribute(value = "area")
	public Area getArea(@RequestParam(required = false) Long id) {
		if (id != null) {
			return areaService.findById(id);
		} else {
			return new Area();
		}
	}

	/**
	 * 展示区域的层级关系
	 * 
	 * @param area
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:area:view")
	@RequestMapping(value = { "list", "" })
	public String list(Area area, Model model) {
		// User user = UserUtils.getUser();
		// if(user.isAdmin()){
		area.setId(1L);
		// }else{
		// area.setId(user.getArea().getId());
		// }
		model.addAttribute("area", area);
		List<Area> list = Lists.newArrayList();
		List<Area> sourcelist = areaService.findAll();
		Area.sortList(list, sourcelist, area.getId());
		model.addAttribute("list", list);
		return "modules/sys/areaList";
	}

	/**
	 * 添加和修改页面的展示页面
	 * 
	 * @param area
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:area:view")
	@RequestMapping(value = "form")
	public String form(Area area, Model model) {
		if (area.getParent() == null || area.getParent().getId() == null) {
			area.setParent(UserUtils.getUser().getOffice().getArea());
		}
		area.setParent(areaService.findById(area.getParent().getId()));
		model.addAttribute("area", area);
		return "modules/sys/areaForm";
	}

	/**
	 * 保存区域对象
	 * 
	 * @param area
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:area:edit")
	@RequestMapping(value = "save")
	public String save(Area area, Model model,
			RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, area)) {
			return form(area, model);
		}
		areaService.save(area);
		addMessage(redirectAttributes, "保存区域'" + area.getName() + "'成功");
		return "redirect:" + GlobalSetting.getAdminPath() + "/sys/area/";
	}

	/**
	 * 删除区域
	 * 
	 * @param id
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:area:edit")
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		if (Area.isAdmin(id)) {
			addMessage(redirectAttributes, "删除区域失败, 不允许删除顶级区域或编号为空");
		} else {
			areaService.delete(id);
			addMessage(redirectAttributes, "删除区域成功");
		}
		return "redirect:" + GlobalSetting.getAdminPath() + "/sys/area/";
	}

	/**
	 * 展示取区域树
	 * 
	 * @param extId
	 * @param response
	 * @return
	 */
	@RequiresUser
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(
			@RequestParam(required = false) Long extId,
			HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		List<Map<String, Object>> mapList = Lists.newArrayList();
		// User user = UserUtils.getUser();
		List<Area> list = areaService.findAll();
		for (int i = 0; i < list.size(); i++) {
			Area e = list.get(i);
			if (extId == null
					|| (extId != null && !extId.equals(e.getId()) && e
							.getParentIds().indexOf("," + extId + ",") == -1)) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				// map.put("pId",
				// !user.isAdmin()&&e.getId().equals(user.getArea().getId())?0:e.getParent()!=null?e.getParent().getId():0);
				map.put("pId", e.getParent() != null ? e.getParent().getId()
						: 0);
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
	
	
	/**
	 * 通过类型获得对应类型的品牌列表
	 * 
	 * @param brandType
	 *            类型
	 * @return
	 */
	@RequestMapping(value = "getAreaByCode", method = RequestMethod.GET)
	public @ResponseBody List<String> getAreaByCode(
			@RequestParam(value = "code") String code) {
		List<String>  codeList = areaService.findAreaByCode(code);
			return codeList;
		
	}
	
	
	/**
	 * 通过类型获得对应类型的品牌列表
	 * 
	 * @param brandType
	 *            类型
	 * @return
	 */
	@RequestMapping(value = "getAreas", method = RequestMethod.GET, headers = { "Accept=application/json" })
	public @ResponseBody List<Area> getAreas(
			@RequestParam(value = "parentId") String parentId) {
		List<Area> areas = areaService.findAreaByParentId(parentId);
		return areas;
	}

}
